<template>
  <div
      class="common-layout"
      :style="{
      height: '100vh',
      width: '100vw',
      backgroundColor: '#072348',
      overflow: 'hidden',
      margin: 0
    }"
  >
    <el-container>
      <el-header>
        <el-row style="padding-left: 30px; padding-top: 10px">
          <el-col :span="1">
            <img src="/imgs/logo.png" style="height: 50px" alt="logo">
          </el-col>
          <el-col :span="1">
            <img src="/imgs/verticalLine.png" style="height: 50px" alt="分割线">
          </el-col>
          <el-col :span="22" style="text-align: left; padding-left: 10px">
            <span style="color:#fff;font-size:30px;font-weight:bold;">舆情监测分析系统</span>
          </el-col>
        </el-row>
      </el-header>
      <el-main>
        <el-row>
          <el-col :span="16">
            <img src="/imgs/background.png" style="width:100%;margin-top:10px;" alt="你网断了">
          </el-col>
          <el-col :span="8">
            <el-card style="margin-top:250px;margin-right:150px">
              <h3 style="text-align:center;">用户登录</h3>
              <el-form label-position="top" style="text-align: left">
                <el-form-item label="邮箱">
                  <div style="display: flex;width: 100%;">
                    <el-input placeholder="请输入邮箱" v-model="email" style="width: 70%"></el-input>
                    <el-select
                        v-model="value"
                        placeholder="Select"
                        style="width: 30%"
                    >
                      <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                  </div>
                </el-form-item>
                <el-form-item label="密码">
                  <el-input placeholder="请输入密码" type="password" v-model="user.password"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" style="width:100%;" @click="login()">登录</el-button>
                </el-form-item>
                <el-form-item>
                  <el-button style="width:100%;" @click="register()">注册</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
    <el-dialog
        v-model="dialogVisible"
        title="注册"
        width="540"
        :before-close="handleClose"
    >
      <el-form :inline="true" :model="form" class="demo-form-inline" label-position="top" style="text-align: left">
        <el-form-item label="用户名">
          <el-input v-model="form.userName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" placeholder="请输入密码" clearable />
        </el-form-item>
        <div style="width: 100%;">
          <el-form-item label="出生日期">
            <el-date-picker
                v-model="form.birthday"
                type="date"
                placeholder="请选择日期"
                clearable
            />
          </el-form-item>
        </div>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" placeholder="请输入邮箱" clearable  />
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="form.verificationCode" placeholder="请输入验证码" clearable style="width: 110px; margin-right: 5px;" />
          <el-button :disabled="isDisabled" @click="startCountdown">
            {{ buttonText }}
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="handleRegister">
            注册
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import axios from "axios";
  import {ElMessage, ElMessageBox} from "element-plus";
  import router from "@/router";
  import {ref} from "vue";
  import qs from "qs";

  const email = ref('')

  const user = ref({
    email: '',
    password: ''
  })

  const form = ref({
    userName: '',
    email: '',
    password: '',
    birthday: '',
    verificationCode: ''
  })

  const options = [
    {
      value: '@qq.com',
      label: '@qq.com',
    },
    {
      value: '@163.com',
      label: '@163.com',
    },
    {
      value: '@sina.com',
      label: '@sina.com',
    },
  ]

  const value = ref('@qq.com')
  const dialogVisible = ref(false)

  // 用户登录处理
  const login = () => {
    // console.log('登录');
    user.value.email = email.value + value.value
    let data = qs.stringify(user.value, {encode: false})
    console.log(data);
    axios.post(window.BASE_URL + '/user/login', data).then(res => {
      console.log(res);
      if (res.data.flag) {
        ElMessage.success(res.data.msg)
        // console.log(JSON.stringify(res.data.data.userName));
        // console.log(localStorage.getItem('user'));
        localStorage.user = JSON.stringify(res.data.data)
        // localStorage.setItem('user', JSON.stringify(res.data.data.userName));
        // console.log(localStorage.getItem('user'));
        router.push('/')
      } else {
        ElMessage.error(res.data.msg)
      }
    })
  }

  // 用户注册处理
  const register = () => {
    dialogVisible.value = true
  }

  const handleRegister = () => {
    let data = qs.stringify(form.value, {encode: false})
    axios.post(window.BASE_URL + '/user/register', data).then(res => {
      if (res.data.flag) {
        ElMessage.success(res.data.msg)
        Object.keys(form.value).forEach(key => {
          form.value[key as keyof typeof form.value] = '';
        })
        dialogVisible.value = false
      } else {
        ElMessage.error(res.data.msg)
      }
    })
  }

  const isDisabled = ref(false); // 是否禁用按钮
  const buttonText = ref('获取验证码'); // 按钮显示文本
  const countdownTime = ref(60); // 倒计时时间（秒）

  const startCountdown = () => {
    if (isDisabled.value) return; // 如果按钮已禁用，直接返回

    if (form.value.email === '') {
      ElMessage.error('邮箱为空')
    } else {
      isDisabled.value = true; // 禁用按钮
      const timer = setInterval(() => {
        countdownTime.value--;
        buttonText.value = `${countdownTime.value}秒`;

        if (countdownTime.value === 0) {
          clearInterval(timer); // 停止计时器
          isDisabled.value = false; // 启用按钮
          buttonText.value = '重新获取';
          countdownTime.value = 60; // 重置倒计时时间
        }
      }, 1000);

      axios.post(window.BASE_URL + '/user/register/sendCode?email=' + form.value.email).then(res => {
        if (res.data.flag) {
          ElMessage.success(res.data.msg)
        } else {
          ElMessage.error(res.data.msg)
        }
      })
    }
  };

  const handleClose = (done: () => void) => {
    ElMessageBox.confirm('是否要取消注册', {
      confirmButtonText: '确定',
      cancelButtonText: '返回',
      type: 'warning'
    }).then(() => {
      Object.keys(form.value).forEach(key => {
        form.value[key as keyof typeof form.value] = '';
      })
      done()
    }).catch(() => {

    })
  }

  const close = (done: () => void) => {
    ElMessageBox.confirm('是否要取消注册', '退出', {
      confirmButtonText: '确定',
      cancelButtonText: '返回',
      type: 'warning'
    }).then(() => {
      Object.keys(form.value).forEach(key => {
        form.value[key as keyof typeof form.value] = '';
      })
      dialogVisible.value = false
    }).catch(() => {

    })
  }
</script>

<style scoped lang="scss">
  /* 覆盖 Element Plus 容器的默认内边距 */
  :deep(.el-container) {
    margin: 0;
    padding: 0;
  }
  :deep(.el-header),
  :deep(.el-main) {
    padding: 0 !important;
  }

  .demo-form-inline .el-input {
    --el-input-width: 220px;
  }

  .demo-form-inline .el-select {
    --el-select-width: 220px;
  }
</style>